package com.jnu.accounthelper.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jnu.accounthelper.EditAccountActivity;
import com.jnu.accounthelper.R;
import com.jnu.accounthelper.db.Account;
import com.jnu.accounthelper.db.DBManager;
import com.jnu.accounthelper.ui.home.HomeFragment;
import com.jnu.accounthelper.ui.slideshow.AccountFragment;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ManageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ManageFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public static final int RESULT_CODE_ADD_DATA = 996;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ArrayList<Account> accounts;
    private RecyclerView recyclerView;
    private ManageFragment.MyRecyclerViewAdapter adapter;
    private com.google.android.material.floatingactionbutton.FloatingActionButton fab;
    private TextView total;
    private HashMap<String,Integer> hash= new HashMap<>();

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String name=data.getStringExtra("type");
                String n=data.getStringExtra("number");
                String source =data.getStringExtra("source");
                String remark =data.getStringExtra("remark");
                int image=data.getIntExtra("image", R.drawable.other);
                int num=Integer.parseInt(n);
                int position=data.getIntExtra("position",accounts.size());
                Account account=new Account(name,remark,num,image,source);
                accounts.add(position,account);
                accounts.get(position).setType(name);
                accounts.get(position).setNumber(num);
                DBManager.insertToAccount(account);
                setData();
                adapter.notifyDataSetChanged();

                //更新数据显示
                double sum=DBManager.getSum();
                total.setText(String.valueOf(sum));

            }
        }
    });
    public ManageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ManageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ManageFragment newInstance(String param1, String param2) {
        ManageFragment fragment = new ManageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_manage, container, false);

        hash.put("微信",R.drawable.wechat);
        hash.put("支付宝",R.drawable.zhifubao);
        hash.put("银行卡",R.drawable.card);
        hash.put("现金",R.drawable.cash);

        recyclerView=root.findViewById(R.id.recycle_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new ManageFragment.MyRecyclerViewAdapter(accounts);
        recyclerView.setAdapter(adapter);
        setData();

        total=root.findViewById(R.id.total_number);
        double sum=DBManager.getSum();
        total.setText(String.valueOf(sum));
        fab=root.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ManageFragment.this.getContext(), EditAccountActivity.class);
                intent.putExtra("position",0);
                launcherAdd.launch(intent);
            }
        });

        return root;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void setData(){
        try {
            accounts= DBManager.getAccountList();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ArrayList<Account> new_list=new ArrayList<>();
        Map<String, List<Account>> bmListMap = new HashMap<String, List<Account>>();
        bmListMap = accounts.stream().collect(Collectors.groupingBy(Account -> Account.getSource()));
        for (Map.Entry<String, List<Account>> entry : bmListMap.entrySet()) {
            List<Account> currnrtbmList = entry.getValue();
            int sum = 0;
            int image = 0;
            String da = new String();
            for (Account account : currnrtbmList) {

                sum += account.getNumber();
                try {
                    image = hash.get(account.getSource());
                } catch (Exception e) {
                    image = R.drawable.other;
                }

                da = account.getDate();
            }
            Account acc;
            if (entry.getKey().equals(""))
                acc = new Account("其他账户", "", sum, image, entry.getKey());
            else acc = new Account(entry.getKey(), "", sum, image, entry.getKey());
            acc.setDate(da);
            new_list.add(acc);
        }
        accounts=new_list;
    }
    private class MyRecyclerViewAdapter extends RecyclerView.Adapter{
        //private ArrayList<Account> accounts;


        public MyRecyclerViewAdapter(ArrayList<Account> accounts) {

        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.account_item_holder, parent, false);
            return new ManageFragment.MyRecyclerViewAdapter.MyViewHolder(view);


        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            ManageFragment.MyRecyclerViewAdapter.MyViewHolder holder =(ManageFragment.MyRecyclerViewAdapter.MyViewHolder)Holder;
            holder.getImageView().setImageResource(accounts.get(position).getCoverResourceId());
            holder.getType().setText(accounts.get(position).getType());
            holder.getNumber().setText(accounts.get(position).getNumber()+"");
            holder.getRemark().setText(accounts.get(position).getRemark());
        }



        @Override
        public int getItemCount() {
            return accounts.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder{

            private final ImageView imageView;
            private final TextView type;
            private final TextView remark;
            private final TextView number;


            public MyViewHolder(View view) {
                super(view);

                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.type=view.findViewById(R.id.type);
                this.remark=view.findViewById(R.id.remark);
                this.number=view.findViewById(R.id.number);


            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getType() {
                return type;
            }

            public TextView getRemark() {
                return remark;
            }

            public TextView getNumber() {
                return number;
            }





        }
    }
}